// pages/login/login.ts
import { getUserInfo } from '@/api/custom'
import { login } from '@/api/admin'
import { toast } from '@/utils/extendApi'
// 导入 ComponentWithStore 方法
import { ComponentWithStore } from 'mobx-miniprogram-bindings'
// 导入 store 对象
import { userStore } from '@/store/userstore'
ComponentWithStore({
  // 让页面和 Store 对象建立关联
  storeBindings: {
    store: userStore,
    fields: [],
    actions: ['setLoginInfo', 'setUserInfo']
  },
  /**
   * 页面的初始数据
   */
  data: {
    agreement: false
  },
  methods: {
    logins() {
      if (!this.data.agreement) {
        toast({
          title: '请阅读并同意服务协议和隐私政策', //提示的内容
          duration: 2000, //持续的时间
          icon: 'none', //图标有success、error、loading、none四种
          mask: true //显示透明蒙层 防止触摸穿透
        })
      }
      wx.login({
        success: ({ code }) => {
          if (!code) {
            toast({ title: '授权失败' })
            return
          }
          const loginData = {
            loginName: code,
            password: null,
            type: 'WECHAT'
          }
          login(loginData).then(data => {
            const user = data.data
            user.cTime = Date.now()
            this.setLoginInfo(user)
            this.getUserInfo()
            wx.navigateBack({
              delta: 1
            });
          })
        }
      })
    },
    async getUserInfo() {
      await getUserInfo("").then(data => {
        this.setUserInfo(data.data)
      })
    },
    agreement() {
      const agreement = !this.data.agreement
      this.setData({
        agreement: agreement
      })
    }
  }
})